package com.joshua.spring.exception;

import com.joshua.spring.entity.em.ResponseEnum;
import com.joshua.spring.entity.vo.GlobalResponse;
import com.joshua.spring.util.JacksonUtils;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * projectName dragon-cloud
 * package com.joshua.spring.exception
 * classname  ExceptionErrorDecoder
 * <p>
 * description
 * </p>
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/8/29 11:18
 */
@Slf4j
@Configuration
public class ExceptionErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        InnerServiceException innerServiceException;
        try {
            String json = Util.toString(response.body().asReader());
            GlobalResponse globalResponse = JacksonUtils.getDefaultInstance().readValue(json, GlobalResponse.class);
            if (ResponseEnum.getRequestBreakingCodes().contains(globalResponse.getErrorMsg().getECode())) {
                //如果在需要熔断的异常列表中，则进入熔断
                return new MicroServiceException(globalResponse);
            }
            //否则向上游服务抛出异常
            innerServiceException = new InnerServiceException(globalResponse);
            log.info("Feign client global exception handler catch exception", innerServiceException);
            return innerServiceException;
        } catch (IOException e) {
            log.info("Feign client global exception handler catch exception", e);
            innerServiceException = new InnerServiceException(GlobalResponse.buildFail());
        }
        return innerServiceException;
    }
}
